//
//  LSSearchViewController.m
//  LibraryStorm
//
//  Created by Enel@Lightning on 3/23/14.
//  Copyright (c) 2014 3ATeam. All rights reserved.
//

#import "LSSearchViewController.h"
#import "LSMainViewController.h"

#import "LSCoreDataController.h"
#import "BookDetail.h"

#import "UIColor+HexString.h"
#import "LSSearchCell.h"
#import "LSSearchCell+ConfigureForBook.h"

static NSString * const SearchCellIdentifier = @"SearchCellId";
@interface LSSearchViewController ()

@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) NSArray *searchResults;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@end

@implementation LSSearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    // TODO: Custom background color
    [self.view setBackgroundColor:[UIColor colorWithHexString:Color_Orange_View]];
    [self.tableView setBackgroundColor:[UIColor whiteColor]];
    self.managedObjectContext = [[LSCoreDataController sharedInstance] newManagedObjectContext];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.searchBar becomeFirstResponder];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self registerForKeyboardNotifications];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController.navigationBar setTranslucent:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSSearchCell *cell = [self.tableView dequeueReusableCellWithIdentifier:SearchCellIdentifier forIndexPath:indexPath];
    if (indexPath.row < self.searchResults.count) {
        BookDetail *book = [self.searchResults objectAtIndex:indexPath.row];
        [cell configureForBook:book];
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate
/**
 * Method name: tableView:didSelectRowAtIndexPath
 * Description: Dismiss searchViewController. Then show bookDetailViewController from mainViewController using method showBookDetail:
 * Parameters: UITableView, NSIndexPath
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSMainViewController *mainViewController = nil;
    if ([self.presentingViewController isKindOfClass:[MMDrawerController class]]) {
        MMDrawerController *mm_drawerController = (MMDrawerController *)self.presentingViewController;
        if ([mm_drawerController.centerViewController isKindOfClass:[UINavigationController class]]) {
            if ([[(UINavigationController *)mm_drawerController.centerViewController topViewController] isKindOfClass:[LSMainViewController class]]) {
                mainViewController = (LSMainViewController *)[(UINavigationController *)mm_drawerController.centerViewController topViewController];
            }
        }
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
        BookDetail *book = nil;
        if (indexPath.row < self.searchResults.count) {
            book = [self.searchResults objectAtIndex:indexPath.row];
        }
        if (book && mainViewController) {
            [mainViewController showBookDetailWithID:[book objectID]];
        }
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return IS_DEVICE_IPAD ? 64 : 44;
}

#pragma mark - SearchBar Delegate
/**
 * Method name: SearchBar Delegate
 * Description: Filter book when user change text field
 * Parameters: UISearchBar
 */
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if ([searchBar isFirstResponder]) {
        [searchBar resignFirstResponder];
    }
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.searchResults = [NSArray new];
    if (searchText.length > 0) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@ OR author CONTAINS[cd] %@", searchText, searchText];
        self.searchResults = [BookDetail getAllObjectsInContext:self.managedObjectContext withSortDescriptor:nil withPredicate:predicate resetContext:NO fetchLimit:0];
    }
    
    [self.tableView reloadData];
}

#pragma mark - Scroll View
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    if (Device_Orientation == UIInterfaceOrientationPortrait) {
        [_tableView setContentInset:UIEdgeInsetsMake(0, 0, kbSize.height, 0)];
    }else {
        [_tableView setContentInset:UIEdgeInsetsMake(0, 0, kbSize.width, 0)];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [_tableView setContentInset:UIEdgeInsetsZero];
    [_tableView scrollRectToVisible:CGRectMake(0, 0, _tableView.bounds.size.width, 87.0f) animated:YES];
}
@end
